// 封装cartStore购物车模块
import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useUserStore } from './user'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart"


export const useCartStore = defineStore('cart',()=>{
  const cartList = ref([])
  // 抽象一个获取购物车列表的方法
  const UpdataNewList = async ()=>{
    const res = await findNewCartListAPI()
    cartList.value = res.result 
  }
  const userStore = useUserStore()
  const isLogin = computed(()=> userStore.userInfo.token) 
  
  const addCart = async(goods) => {
    
    // 添加购物车执行逻辑
    // 判断是否登录
    if(isLogin.value){
      // 登录之后的购物车逻辑
      const {skuId,count} = goods
      await insertCartAPI({skuId,count})
      UpdataNewList()
    }else{
      // 本地购物车逻辑
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      // 如果存在count数量相加
      if(item) {
        item.count = item.count + goods.count
      }else {
        // 不存在push到购物车列表中
        cartList.value.push(goods)
      }
    
    }
    
  }
  const delCart = async(skuId) => {
    if(isLogin.value){
      // 调用删除接口
      await delCartAPI([skuId])
      UpdataNewList()
    }else{
      const idX= cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(idX,1)
    }
  } 
  // 清除购物车
  const clearCart = () => {
    cartList.value = [] 
  }  
 
  // 计算属性
  const allCount = computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
  const allPrice = computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price,0))
  // 订单也数据统计
  const selectedCount = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count,0))
  const selectedPrice = computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count*c.price,0))
  // 全选
  const isAll = computed(()=>cartList.value.every((item)=>item.selected))
  const allCheck =(selected) => {
    cartList.value.forEach(item=>item.selected = selected)
  }
  // 单选
  const singleCheck = (skuId,selected) => {
    const item  = cartList.value.find((item)=>item.skuId === skuId)
    item.selected = selected
  }
  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    singleCheck,
    allCheck,
    clearCart,
    UpdataNewList
  }

},{
  persist: true,
})